% if newsletter:
<%!
    import json
    from plexpy import notifiers
    from plexpy.helpers import anon_url, checked

    all_notifiers = sorted(notifiers.get_notifiers(), key=lambda k: (k['agent_label'].lower(), k['friendly_name'], k['id']))
    email_notifiers = [n for n in all_notifiers if n['agent_name'] == 'email']
    email_notifiers = [{'id': 0, 'agent_label': 'New Email Configuration', 'friendly_name': ''}] + email_notifiers
    other_notifiers = [{'id': 0, 'agent_label': 'Select a Notification Agent', 'friendly_name': ''}] + all_notifiers
%>
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-remove"></i></button>
            <h4 class="modal-title" id="newsletter-config-modal-header">${newsletter['agent_label']} Newsletter Settings &nbsp;<small><span class="newsletter_id">(Newsletter ID: ${newsletter['id']}${' - ' + newsletter['friendly_name'] if newsletter['friendly_name'] else ''})</span></small></h4>
        </div>
        <div class="modal-body">
            <div class="container-fluid">
                <div class="row">
                    <ul class="nav nav-tabs list-unstyled" role="tablist">
                        <li role="presentation" class="active"><a href="#tabs-newsletter_config" aria-controls="tabs-newsletter_config" role="tab" data-toggle="tab">Configuration</a></li>
                        <li role="presentation"><a href="#tabs-newsletter_saving_sending" aria-controls="tabs-newsletter_saving_sending" role="tab" data-toggle="tab">Saving & Sending</a></li>
                        <li role="presentation"><a href="#tabs-newsletter_text" aria-controls="tabs-newsletter_text" role="tab" data-toggle="tab">Newsletter Text</a></li>
                        <li role="presentation"><a href="#tabs-test_newsletter" aria-controls="tabs-test_newsletter" role="tab" data-toggle="tab">Test Newsletter</a></li>
                    </ul>
                </div>
                <form action="set_newsletter_config" method="post" class="form" id="set_newsletter_config" data-parsley-validate>
                    <div class="tab-content">
                        <div role="tabpanel" class="tab-pane active" id="tabs-newsletter_config">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="checkbox" style="margin-bottom: 20px;">
                                        <label>
                                            <input type="checkbox" data-id="active_value" class="checkboxes" value="1" autocomplete="off" ${checked(newsletter['active'])}> Enable the Newsletter
                                        </label>
                                        <input type="hidden" id="active_value" name="active" value="${newsletter['active']}">
                                    </div>
                                    <div class="form-group">
                                        <label for="custom_cron">Schedule</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <select class="form-control" id="custom_cron" name="newsletter_config_custom_cron" autocomplete="off">
                                                    <option value="0" ${'selected' if newsletter['config']['custom_cron'] == 0 else ''}>Simple</option>
                                                    <option value="1" ${'selected' if newsletter['config']['custom_cron'] == 1 else ''}>Custom</option>
                                                </select>
                                                <input type="text" id="cron_value" name="cron" value="${newsletter['cron']}" autocomplete="off" />
                                                <div id="cron-widget"></div>
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            <span id="simple_cron_message">Set the schedule for the newsletter.</span>
                                            <span id="custom_cron_message">
                                                Set the schedule for the newsletter using a <a href="${anon_url('https://crontab.guru')}" target="_blank" rel="noreferrer">custom crontab</a>.
                                                <a href="${anon_url('https://apscheduler.readthedocs.io/en/3.x/modules/triggers/cron.html#expression-types')}" target="_blank" rel="noreferrer">Click here</a> for a list of supported expressions.
                                            </span>
                                        </p>
                                    </div>
                                    <div class="form-group">
                                        <label for="time_frame">Time Frame</label>
                                        <div class="row">
                                            <div class="col-md-5">
                                                <div class="input-group newsletter-time_frame">
                                                    <span class="input-group-addon form-control btn-dark inactive">Last</span>
                                                    <input type="number" class="form-control" id="newsletter_config_time_frame" name="newsletter_config_time_frame" value="${newsletter['config']['time_frame']}" autocomplete="off">
                                                    <select class="form-control" id="newsletter_config_time_frame_units" name="newsletter_config_time_frame_units" autocomplete="off">
                                                        <option value="months" ${'selected' if newsletter['config']['time_frame_units'] == 'months' else ''}>months</option>
                                                        <option value="days" ${'selected' if newsletter['config']['time_frame_units'] == 'days' else ''}>days</option>
                                                        <option value="hours" ${'selected' if newsletter['config']['time_frame_units'] == 'hours' else ''}>hours</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        <p class="help-block">Set the time frame to include in the newsletter.</p>
                                    </div>
                                </div>
                                <div class="col-md-12 modal-config-section">
                                    <input type="hidden" id="newsletter_id" name="newsletter_id" value="${newsletter['id']}" />
                                    <input type="hidden" id="agent_id" name="agent_id" value="${newsletter['agent_id']}" />
                                    % for item in newsletter['config_options']:
                                    % if item['input_type'] == 'help':
                                    <div class="form-group">
                                        <label>${item['label']}</label>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % elif item['input_type'] == 'text' or item['input_type'] == 'password':
                                    <div class="form-group">
                                        <label for="${item['name']}">${item['label']}</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="${item['input_type']}" class="form-control" id="${item['name']}" name="${item['name']}" value="${item['value']}" size="30" autocomplete="off" ${'readonly' if item.get('readonly') else ''}>
                                            </div>
                                        </div>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % elif item['input_type'] == 'number':
                                    <div class="form-group">
                                        <label for="${item['name']}">${item['label']}</label>
                                        <div class="row">
                                            <div class="col-md-3">
                                                <input type="${item['input_type']}" class="form-control" id="${item['name']}" name="${item['name']}" value="${item['value']}" size="30" autocomplete="off">
                                            </div>
                                        </div>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % elif item['input_type'] == 'button':
                                    <div class="form-group">
                                        <label for="${item['name']}">${item['label']}</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="button" class="btn btn-bright" id="${item['name']}" name="${item['name']}" value="${item['value']}">
                                            </div>
                                        </div>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % elif item['input_type'] == 'checkbox':
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" data-id="${item['name']}" class="checkboxes" value="1" autocomplete="off" ${checked(item['value'])}> ${item['label']}
                                        </label>
                                        <p class="help-block">${item['description'] | n}</p>
                                        <input type="hidden" id="${item['name']}" name="${item['name']}" value="${item['value']}">
                                    </div>
                                    % elif item['input_type'] == 'select':
                                    <div class="form-group">
                                        <label for="${item['name']}">${item['label']}</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <select class="form-control" id="${item['name']}" name="${item['name']}" autocomplete="off">
                                                    % for key, value in sorted(item['select_options'].items()):
                                                    % if key == item['value']:
                                                    <option value="${key}" selected>${value}</option>
                                                    % else:
                                                    <option value="${key}">${value}</option>
                                                    % endif
                                                    % endfor
                                                </select>
                                            </div>
                                        </div>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % elif item['input_type'] == 'selectize':
                                    <div class="form-group">
                                        <label for="${item['name']}">${item['label']}</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <select class="form-control" id="${item['name']}" name="${item['name']}" autocomplete="off">
                                                    % if item['select_all']:
                                                    <option value="select-all">Select All</option>
                                                    <option value="remove-all">Remove All</option>
                                                    % endif
                                                    % if isinstance(item['select_options'], dict):
                                                    % for section, options in item['select_options'].items():
                                                    <optgroup label="${section}">
                                                        % for option in sorted(options, key=lambda x: x['text'].lower()):
                                                            <option value="${option['value']}">${option['text']}</option>
                                                        % endfor
                                                    </optgroup>
                                                    % endfor
                                                    % else:
                                                    % if item['select_all']:
                                                    <option value="border-all"></option>
                                                    % endif
                                                    % for option in sorted(item['select_options'], key=lambda x: x['text'].lower()):
                                                        <option value="${option['value']}">${option['text']}</option>
                                                    % endfor
                                                    % endif
                                                </select>
                                            </div>
                                        </div>
                                        <p class="help-block">${item['description'] | n}</p>
                                    </div>
                                    % endif
                                    % endfor
                                </div>
                                <div class="col-md-12 modal-config-section">
                                    <div class="form-group">
                                        <label for="id_name">Unique ID Name</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="text" class="form-control" id="id_name" name="id_name" value="${newsletter['id_name']}" size="30" autocomplete="off">
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Optional: Enter a unique ID name to create a static URL to the <em>last sent scheduled newsletter</em> at <span class="inline-pre">${http_root}newsletter/id/&lt;id_name&gt;</span>.
                                            Only letters (a-z), numbers (0-9), underscores (_) and hyphens (-) are allowed. Leave blank to disable.<br>
                                            Note: Test newsletters are not considered scheduled newsletters.
                                        </p>
                                    </div>
                                    <div class="form-group">
                                        <label for="friendly_name">Description</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="text" class="form-control" id="friendly_name" name="friendly_name" value="${newsletter['friendly_name']}" size="30" autocomplete="off">
                                            </div>
                                        </div>
                                        <p class="help-block">Optional: Enter a description to help identify this newsletter in the newsletters list.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="tabs-newsletter_saving_sending">
                            <div class="row">
                                <div class="col-md-12">
                                    <label>Saving</label>
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" id="newsletter_config_save_only_checkbox" data-id="newsletter_config_save_only" class="checkboxes" value="1" autocomplete="off" ${checked(newsletter['config']['save_only'])}> Save HTML File Only
                                        </label>
                                        <p class="help-block">Enable to save the newsletter HTML file without sending it to any notification agent.</p>
                                        <input type="hidden" id="newsletter_config_save_only" name="newsletter_config_save_only" value="${newsletter['config']['save_only']}">
                                    </div>
                                    <div class="form-group">
                                        <label for="newsletter_config_filename">HTML File Name</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="text" class="form-control" id="newsletter_config_filename" name="newsletter_config_filename" value="${newsletter['config']['filename']}" size="30" autocomplete="off">
                                            </div>
                                        </div>
                                        <p class="help-block">Optional: Enter the file name to use when saving the newsletter (ending with <span class="inline-pre">.html</span>). You may use any of the <a href="#newsletter-text-sub-modal" data-toggle="modal">newsletter text parameters</a>. Leave blank for default.</p>
                                    </div>
                                </div>
                                <div class="col-md-12 modal-config-section" id="newsletter_agent_options">
                                    <label>Sending</label>
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" id="newsletter_config_formatted_checkbox" data-id="newsletter_config_formatted" class="checkboxes" value="1" autocomplete="off" ${checked(newsletter['config']['formatted'])}> Send Newsletter as an HTML Formatted Email
                                        </label>
                                        <p class="help-block">Enable to send the newsletter as an HTML formatted Email. Disable to only send a subject and body message to a different notification agent.</p>
                                        <input type="hidden" id="newsletter_config_formatted" name="newsletter_config_formatted" value="${newsletter['config']['formatted']}">
                                    </div>
                                    <div class="form-group" id="email_notifier_select">
                                        <div class="checkbox">
                                            <label>
                                                <input type="checkbox" id="newsletter_config_threaded_checkbox" data-id="newsletter_config_threaded" class="checkboxes" value="1" autocomplete="off" ${checked(newsletter['config']['threaded'])}> Enable Grouped Email Thread
                                            </label>
                                            <p class="help-block">Enable to group this newsletter together in a single Email thread. Disable to send a new Email for each newsletter.</p>
                                            <input type="hidden" id="newsletter_config_threaded" name="newsletter_config_threaded" value="${newsletter['config']['threaded']}">
                                        </div>
                                        <label for="newsletter_email_notifier_id">Email Notification Agent</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <select class="form-control" id="newsletter_email_notifier_id" name="newsletter_email_notifier_id" autocomplete="off">
                                                    % for notifier in email_notifiers:
                                                    <% selected = 'selected' if notifier['id'] == newsletter['email_config']['notifier_id'] else '' %>
                                                    % if notifier['friendly_name']:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']} (${notifier['id']} - ${notifier['friendly_name']})</option>
                                                    % elif notifier['id']:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']} (${notifier['id']})</option>
                                                    % else:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']}</option>
                                                    % endif
                                                    % endfor
                                                </select>
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Select an existing Email notification agent or enter a new configuration below.<br>
                                            Note: Make sure HTML support is enabled for the Email notification agent.
                                        </p>
                                    </div>
                                    <div class="form-group" id="other_notifier_select">
                                        <label for="newsletter_config_notifier_id">Notification Agent</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <select class="form-control" id="newsletter_config_notifier_id" name="newsletter_config_notifier_id" autocomplete="off">
                                                    % for notifier in other_notifiers:
                                                    <% selected = 'selected' if notifier['id'] == newsletter['config']['notifier_id'] else '' %>
                                                    % if notifier['friendly_name']:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']} (${notifier['id']} - ${notifier['friendly_name']})</option>
                                                    % elif notifier['id']:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']} (${notifier['id']})</option>
                                                    % else:
                                                    <option value="${notifier['id']}" ${selected}>${notifier['agent_label']}</option>
                                                    % endif
                                                    % endfor
                                                </select>
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Select an existing notification agent where the subject and body text will be sent.<br>
                                            Note: Self-hosted newsletters must be enabled under <a data-tab-destination="notifications" data-dismiss="modal" data-target="newsletter_self_hosted">Newsletters</a> to include a link to the newsletter.
                                        </p>
                                    </div>
                                    <div id="newsletter-email-config">
                                        % for item in newsletter['email_config_options']:
                                        % if item['input_type'] == 'help':
                                        <div class="form-group">
                                            <label>${item['label']}</label>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % elif item['input_type'] == 'text' or item['input_type'] == 'password':
                                        <div class="form-group">
                                            <label for="${item['name']}">${item['label']}</label>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <input type="${item['input_type']}" class="form-control" id="${item['name']}" name="${item['name']}" value="${item['value']}" size="30" autocomplete="off" ${'readonly' if item.get('readonly') else ''}>
                                                </div>
                                            </div>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % elif item['input_type'] == 'number':
                                        <div class="form-group">
                                            <label for="${item['name']}">${item['label']}</label>
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <input type="${item['input_type']}" class="form-control" id="${item['name']}" name="${item['name']}" value="${item['value']}" size="30" autocomplete="off">
                                                </div>
                                            </div>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % elif item['input_type'] == 'button':
                                        <div class="form-group">
                                            <label for="${item['name']}">${item['label']}</label>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <input type="button" class="btn btn-bright" id="${item['name']}" name="${item['name']}" value="${item['value']}">
                                                </div>
                                            </div>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % elif item['input_type'] == 'checkbox' and item['name'] != 'newsletter_email_html_support':
                                        <div class="checkbox">
                                            <label>
                                                <input type="checkbox" data-id="${item['name']}" class="checkboxes" value="1" autocomplete="off" ${checked(item['value'])}> ${item['label']}
                                            </label>
                                            <p class="help-block">${item['description'] | n}</p>
                                            <input type="hidden" id="${item['name']}" name="${item['name']}" value="${item['value']}">
                                        </div>
                                        % elif item['input_type'] == 'select':
                                        <div class="form-group">
                                            <label for="${item['name']}">${item['label']}</label>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <select class="form-control" id="${item['name']}" name="${item['name']}" autocomplete="off">
                                                        % for key, value in sorted(item['select_options'].items()):
                                                        % if isinstance(value, list):
                                                        <optgroup label="${key}">
                                                            % for option in sorted(value, key=lambda x: x['text'].lower()):
                                                                <option value="${option['value']}" ${'selected' if option['value'] == item['value'] else ''}>${option['text']}</option>
                                                            % endfor
                                                        </optgroup>
                                                        % else:
                                                        <option value="${key}" ${'selected' if key == item['value'] else ''}>${value}</option>
                                                        % endif
                                                        % endfor
                                                    </select>
                                                </div>
                                            </div>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % elif item['input_type'] == 'selectize':
                                        <div class="form-group">
                                            <label for="${item['name']}">${item['label']}</label>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <select class="form-control" id="${item['name']}" name="${item['name']}" autocomplete="off">
                                                        <option value="select-all">Select All</option>
                                                        <option value="remove-all">Remove All</option>
                                                        % if isinstance(item['select_options'], dict):
                                                        % for section, options in item['select_options'].items():
                                                        <optgroup label="${section}">
                                                            % for option in sorted(options, key=lambda x: x['text'].lower()):
                                                                <option value="${option['value']}">${option['text']}</option>
                                                            % endfor
                                                        </optgroup>
                                                        % endfor
                                                        % else:
                                                        <option value="border-all"></option>
                                                        % for option in sorted(item['select_options'], key=lambda x: x['text'].lower()):
                                                            <option value="${option['value']}">${option['text']}</option>
                                                        % endfor
                                                        % endif
                                                    </select>
                                                </div>
                                            </div>
                                            <p class="help-block">${item['description'] | n}</p>
                                        </div>
                                        % endif
                                        % endfor
                                        <input type="hidden" id="newsletter_email_html_support" name="newsletter_email_html_support" value="1">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="tabs-newsletter_text">
                            <label>Newsletter Text</label>
                            <p class="help-block">
                                Set the custom formatted text for each type of notification.
                                <a href="#newsletter-text-sub-modal" data-toggle="modal">Click here</a> for a list of available parameters which can be used.
                            </p>
                            <p class="help-block">
                                You can also add text modifiers to change the case or slice parameters with a list of items.
                                <a href="#notify-text-modifiers-modal" data-toggle="modal">Click here</a> to view usage information.
                            </p>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <label for="subject">Subject</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <input type="text" class="form-control" id="subject" name="subject" value="${newsletter['subject']}" size="30" autocomplete="off">
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Enter a custom subject line for the newsletter. Leave blank for default.
                                        </p>
                                    </div>
                                    <div class="form-group" id="newsletter_body">
                                        <label for="body">Body</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <textarea class="form-control"  id="body" name="body" autocomplete="off" data-autoresize>${newsletter['body']}</textarea>
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Enter a custom body line for the newsletter notification. Leave blank for default.
                                        </p>
                                    </div>
                                    <div class="form-group">
                                        <label for="message">Message</label>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <textarea class="form-control"  id="message" name="message" autocomplete="off" data-autoresize>${newsletter['message']}</textarea>
                                            </div>
                                        </div>
                                        <p class="help-block">
                                            Enter a custom message to include on the newsletter.
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="tabs-test_newsletter">
                            <label>Preview Newsletter</label>
                            <p class="help-block">
                                Preview the ${newsletter['agent_label']} newsletter.
                            </p>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-12">
                                        <input type="button" class="btn btn-bright" id="preview_newsletter" name="preview_newsletter" value="Preview ${newsletter['agent_label']} Newsletter">
                                    </div>
                                </div>
                            </div>
                            <label>Test Newsletter</label>
                            <p class="help-block">
                                Test if the ${newsletter['agent_label']} newsletter is working. Check the <a href="logs">logs</a> for troubleshooting.
                            </p>
                            <p class="help-block">
                                Warning: This will send an actual newsletter to your notification agent!
                            </p>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-12">
                                        <input type="button" class="btn btn-bright" id="test_newsletter" name="test_newsletter" value="Test ${newsletter['agent_label']} Newsletter">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div class="modal-footer">
            <input type="button" id="delete-newsletter-item" class="btn btn-danger btn-edit" style="float:left;" value="Delete">
            <input type="button" id="duplicate-newsletter-item" class="btn btn-dark btn-edit" style="float:left;" value="Duplicate">
            <input type="button" id="save-newsletter-item" class="btn btn-bright" value="Save">
        </div>
    </div>
</div>

<script src="${http_root}js/jquery-cron-min.js"></script>
<script>

    $('#newsletter-config-modal').unbind('hidden.bs.modal');

    var cron_widget = $('#cron-widget').cron({
        initial: '0 0 * * 0',
        classes: 'form-control cron-select',
        onChange: function() {
            $("#cron_value").val($(this).cron('value'));
        }
    });

    if (${newsletter['config']['custom_cron']}) {
        $('#cron_value').val('${newsletter['cron'] | n}');
    } else {
        try {
            cron_widget.cron('value', '${newsletter['cron']}');
        } catch (e) {}
    }

    function toggleCustomCron() {
       if ($('#custom_cron').val() === '1'){
           $('#cron-widget').hide();
           $('#cron_value').show();
           $('#simple_cron_message').hide();
           $('#custom_cron_message').show();
       } else {
           $('#cron-widget').show();
           $('#cron_value').hide();
           $('#simple_cron_message').show();
           $('#custom_cron_message').hide();
       }
    }
    toggleCustomCron();

    $('#custom_cron').change(function () {
        toggleCustomCron();
    });

    function validateFilename() {
        var filename = $('#newsletter_config_filename').val();
        if (filename !== '' && !(filename.endsWith('.html'))) {
            showMsg('<i class="fa fa-times"></i> Failed to save newsletter. Invalid file name.', false, true, 5000, true);
            return false;
        } else {
            return true;
        }
    }

    function validateIDName() {
        var id_name = $('#id_name').val();
        if (/^[a-zA-Z0-9_-]*$/.test(id_name)) {
            return true;
        } else {
            showMsg('<i class="fa fa-times"></i> Failed to save newsletter. Invalid unique ID name.', false, true, 5000, true);
            return false;
        }
    }

    var $incl_libraries = $('#newsletter_config_incl_libraries').selectize({
        plugins: ['remove_button'],
        maxItems: null,
        render: {
            option: function(item) {
                if (item.value.endsWith('-all')) {
                    return '<div class="' + item.value + '">' + item.text + '</div>'
                }
                return '<div>' + item.text + '</div>';
            }
        },
        onItemAdd: function(value) {
            if (value === 'select-all') {
                var all_keys = $.map(this.options, function(option){
                    return option.value.endsWith('-all') ? null : option.value;
                });
                this.setValue(all_keys);
            } else if (value === 'remove-all') {
                this.clear();
                this.refreshOptions();
                this.positionDropdown();
            }
        }
    });
    var incl_libraries = $incl_libraries[0].selectize;
    incl_libraries.setValue(${json.dumps(next((c['value'] for c in newsletter['config_options'] if c['name'] == 'newsletter_config_incl_libraries'), [])) | n});

    initConfigCheckbox('#newsletter_config_save_only_checkbox', '#newsletter_agent_options', true);

    function toggleEmailSelect () {
        if ($('#newsletter_config_formatted_checkbox').is(':checked')) {
            $('#newsletter_body').hide();
            $('#email_notifier_select').show();
            $('#other_notifier_select').hide();
            toggleNewEmailConfig();
        } else {
            $('#newsletter_body').show();
            $('#email_notifier_select').hide();
            $('#other_notifier_select').show();
            $('#newsletter-email-config').hide();
        }
    }
    toggleEmailSelect();

    $('#newsletter_config_formatted_checkbox').change(function () {
        toggleEmailSelect();
    });

    function toggleNewEmailConfig () {
        if ($('#newsletter_config_formatted_checkbox').is(':checked') && $('#newsletter_email_notifier_id').val() === '0') {
            $('#newsletter-email-config').show();
        } else {
            $('#newsletter-email-config').hide();
        }
    }
    toggleNewEmailConfig();

    $('#newsletter_email_notifier_id').change(function () {
        toggleNewEmailConfig();
    });

    var REGEX_EMAIL = '([a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@' +
                      '(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)';
    var $email_selectors = $('#newsletter_email_to, #newsletter_email_cc, #newsletter_email_bcc').selectize({
        plugins: ['remove_button'],
        maxItems: null,
        searchField: ['text', 'value'],
        render: {
            item: function(item, escape) {
                return '<div>' +
                    (item.text ? '<span class="item-text">' + escape(item.text) + '</span>' : '') +
                    (item.value ? '<span class="item-value">' + escape(item.value) + '</span>' : '') +
                '</div>';
            },
            option: function(item, escape) {
                var label = item.text || item.value;
                var caption = item.text ? item.value : null;
                if (item.value.endsWith('-all')) {
                    return '<div class="' + item.value + '">' + escape(label) + '</div>'
                }
                return '<div>' +
                    escape(label) +
                    (caption ? '<span class="caption">' + escape(caption) + '</span>' : '') +
                '</div>';
            }
        },
        onItemAdd: function(value) {
            if (value === 'select-all') {
                var all_keys = $.map(this.options, function(option){
                    return option.value.endsWith('-all') ? null : option.value;
                });
                this.setValue(all_keys);
            } else if (value === 'remove-all') {
                this.clear();
                this.refreshOptions();
                this.positionDropdown();
            }
        },
        createFilter: function(input) {
            var match, regex;

            // email@address.com
            regex = new RegExp('^' + REGEX_EMAIL + '$', 'i');
            match = input.match(regex);
            if (match) return !this.options.hasOwnProperty(match[0]);

            // user <email@address.com>
            regex = new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i');
            match = input.match(regex);
            if (match) return !this.options.hasOwnProperty(match[2]);

            return false;
        },
        create: function(input) {
            if ((new RegExp('^' + REGEX_EMAIL + '$', 'i')).test(input)) {
                return {value: input};
            }
            var match = input.match(new RegExp('^([^<]*)\<' + REGEX_EMAIL + '\>$', 'i'));
            if (match) {
                return {
                    value : match[2],
                    text  : $.trim(match[1])
                };
            }
            return false;
        }
    });
    var email_to = $email_selectors[0].selectize;
    var email_cc = $email_selectors[1].selectize;
    var email_bcc = $email_selectors[2].selectize;
    email_to.setValue(${json.dumps(next((c['value'] for c in newsletter['email_config_options'] if c['name'] == 'newsletter_email_to'), [])) | n});
    email_cc.setValue(${json.dumps(next((c['value'] for c in newsletter['email_config_options'] if c['name'] == 'newsletter_email_cc'), [])) | n});
    email_bcc.setValue(${json.dumps(next((c['value'] for c in newsletter['email_config_options'] if c['name'] == 'newsletter_email_bcc'), [])) | n});

    function reloadModal() {
        $.ajax({
            url: 'get_newsletter_config_modal',
            data: { newsletter_id: '${newsletter["id"]}' },
            cache: false,
            async: true,
            complete: function (xhr, status) {
                $('#newsletter-config-modal').html(xhr.responseText);
            }
        });
    }

    function saveCallback(jqXHR) {
        if (jqXHR) {
            var result = $.parseJSON(jqXHR.responseText);
            var msg = result.message;
            if (result.result == 'success') {
                showMsg('<i class="fa fa-check"></i> ' + msg, false, true, 5000)
            } else {
                showMsg('<i class="fa fa-times"></i> ' + msg, false, true, 5000, true)
            }
        }

        getNewslettersTable();
        toggleRevealTokens();
    }

    function deleteCallback() {
        $('#newsletter-config-modal').modal('hide');
        getNewslettersTable();
    }

    function duplicateCallback(result) {
        // Set new newsletter id
        $('#newsletter_id').val(result.newsletter_id);
        // Clear friendly name
        $('#friendly_name').val("");

        saveNewsletter();

        $('#newsletter-config-modal').on('hidden.bs.modal', function () {
            loadNewsletterConfig(result.newsletter_id);
        });
        $('#newsletter-config-modal').modal('hide');
    }

    function saveNewsletter() {
        // Trim all text inputs before saving
        $('input[type=text]').val(function(_, value) {
            return $.trim(value);
        });
        // Make sure simple cron value is set
        if ($('#custom_cron').val() === '0'){
            $("#cron_value").val(cron_widget.cron('value'));
        }
        if (validateFilename() && validateIDName()){
            doAjaxCall('set_newsletter_config', $(this), 'tabs', true, true, saveCallback);
        }
    }

    $('#delete-newsletter-item').click(function () {
        var msg = 'Are you sure you want to delete this <strong>${newsletter["agent_label"]}</strong> newsletter?';
        var url = 'delete_newsletter';
        confirmAjaxCall(url, msg, { newsletter_id: '${newsletter["id"]}' }, null, deleteCallback);
    });

    $('#duplicate-newsletter-item').click(function() {
        var msg = 'Are you sure you want to duplicate this <strong>${newsletter["agent_label"]}</strong> newsletter?';
        if ($('#set_newsletter_config .form-control[id$=_password]').val()) {
            msg += '<br><br>Note: Saved passwords will not be copied over and must be re-entered.';
        }
        var url = 'add_newsletter_config';
        confirmAjaxCall(url, msg, { agent_id: '${newsletter["agent_id"]}' }, null, duplicateCallback);
    });

    $('#save-newsletter-item').click(function () {
        saveNewsletter();
    });

    $('#preview_newsletter').click(function () {
        doAjaxCall('set_newsletter_config', $(this), 'tabs', true, false, previewNewsletter);
    });

    $('#test_newsletter').click(function () {
        doAjaxCall('set_newsletter_config', $(this), 'tabs', true, false, sendTestNewsletter);
    });

    function previewNewsletter() {
        showMsg('<i class="fa fa-check"></i>&nbsp; Check pop-up blocker if no response.', false, true, 2000);
        window.open('newsletter_preview?newsletter_id=' + $('#newsletter_id').val());
    }

    function sendTestNewsletter() {
        showMsg('<i class="fa fa-refresh fa-spin"></i>&nbsp; Sending Newsletter', false);
        $.ajax({
            url: 'send_newsletter',
            data: {
                newsletter_id: $('#newsletter_id').val(),
                notify_action: 'test'
            },
            cache: false,
            async: true,
            success: function (data) {
                if (data.result === 'success') {
                    showMsg('<i class="fa fa-check"></i> ' + data.message, false, true, 5000);
                } else {
                    showMsg('<i class="fa fa-exclamation-circle"></i> ' + data.message, false, true, 5000, true);
                }
            }
        });
    }

    $("${', '.join(['#' + c['name'] for c in newsletter['config_options'] if c.get('refresh')])}").on('change', function () {
        // Reload modal to update certain fields
        doAjaxCall('set_newsletter_config', $(this), 'tabs', true, false, reloadModal);
        return false;
    });

    // Never send checkbox values directly, always substitute value in hidden input.
    $('.checkboxes').click(function () {
        var configToggle = $(this).data('id');
        if ($(this).is(':checked')) {
            $('#'+configToggle).val(1);
        } else {
            $('#'+configToggle).val(0);
        }
    });

    // auto resizing textarea for custom notification message body
    $('textarea[data-autoresize]').each(function () {
        var modal_body = $(this).closest('.modal-body');
        var offset = this.offsetHeight - this.clientHeight;
        var resizeTextarea = function (el) {
            var modal_offset = modal_body.scrollTop();
            $(el).css('height', 'auto').css('height', el.scrollHeight + offset);
            modal_body.scrollTop(modal_offset);
        };
        $(this).on('focus keyup input', function () { resizeTextarea(this); }).removeAttr('data-autoresize');
    });

    toggleRevealTokens();
</script>
% else:
<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-remove"></i></button>
            <h4 class="modal-title" id="newsletter-config-modal-header">Error</h4>
        </div>
        <div class="modal-body" style="text-align: center">
            <strong>
                <i class="fa fa-exclamation-circle"></i> Failed to retrieve newsletter configuration. Check the <a href="logs">logs</a> for more info.
            </strong>
        </div>
        <div class="modal-footer">
        </div>
    </div>
</div>
% endif
